﻿namespace CKFinder.Connector.CommandHandlers
{
    using CKFinder;
    using CKFinder.Connector;
    using System;
    using System.Globalization;
    using System.IO;
    using System.Xml;

    internal class GetFilesCommandHandler : XmlCommandHandlerBase
    {
        protected override void BuildXml()
        {
            if (!base.CurrentFolder.CheckAcl(AccessControlRules.FileView))
            {
                ConnectorException.Throw(0x67);
            }
            string serverPath = base.CurrentFolder.ServerPath;
            bool flag = (base.Request.QueryString["showThumbs"] != null) && base.Request.QueryString["showThumbs"].ToString().Equals("1");
            XmlNode node = XmlUtil.AppendElement(base.ConnectorNode, "Files");
            DirectoryInfo info = new DirectoryInfo(serverPath);
            foreach (FileInfo info2 in info.GetFiles())
            {
                string extension = Path.GetExtension(info2.Name);
                if (!Config.Current.CheckIsHiddenFile(info2.Name) && base.CurrentFolder.ResourceTypeInfo.CheckExtension(extension))
                {
                    decimal num2 = Math.Round((decimal) (info2.Length / 1024M));
                    if ((num2 < 1M) && (info2.Length != 0L))
                    {
                        num2 = 1M;
                    }
                    XmlNode node2 = XmlUtil.AppendElement(node, "File");
                    XmlUtil.SetAttribute(node2, "name", info2.Name);
                    XmlUtil.SetAttribute(node2, "date", info2.LastWriteTime.ToString("yyyyMMddHHmm"));
                    if ((Config.Current.Thumbnails.Enabled && (Config.Current.Thumbnails.DirectAccess || flag)) && ImageTools.IsImageExtension(extension.TrimStart(new char[] { '.' })))
                    {
                        bool flag2 = false;
                        try
                        {
                            flag2 = File.Exists(Path.Combine(base.CurrentFolder.ThumbsServerPath, info2.Name));
                        }
                        catch
                        {
                        }
                        if (flag2)
                        {
                            XmlUtil.SetAttribute(node2, "thumb", info2.Name);
                        }
                        else if (flag)
                        {
                            XmlUtil.SetAttribute(node2, "thumb", "?" + info2.Name);
                        }
                    }
                    XmlUtil.SetAttribute(node2, "size", num2.ToString(CultureInfo.InvariantCulture));
                }
            }
        }
    }
}

